package com.markerhub.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DateTime;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.annotation.JsonFormat;
import com.google.common.collect.Maps;
import com.markerhub.common.dto.LoginDto;
import com.markerhub.common.dto.WeiboDto;
import com.markerhub.common.lang.Result;
import com.markerhub.entity.Pic;
import com.markerhub.entity.User;
import com.markerhub.entity.Weibo;
import com.markerhub.service.BlogService;
import com.markerhub.service.PicService;
import com.markerhub.service.WeiboService;
import com.markerhub.util.ShiroUtil;

import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import weibo4j.http.ImageItem;
import weibo4j.model.PostParameter;
import weibo4j.model.WeiboException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.sql.Timestamp;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.logging.Logger;
import weibo4j.Log;

//@RequiresAuthentication
@RestController
public class WeiboController {

    public static String getUUID32(){
        return UUID.randomUUID().toString().replace("-", "").toLowerCase();
    }
    @Autowired
  WeiboService weiboService;

    @Autowired
  PicService picService;

    @Value("${webconfig.path}")
    public String path;
//   获取图片类的方法
    public ImageItem getPicFile(String Name) throws IOException, WeiboException {

        Pic pic = picService.getOne(new QueryWrapper<Pic>().eq("Name",Name));
        Log.logInfo("找到图片数据"+pic.toString());
        String path  =pic.getPath();
        String name = pic.getName();
        File image  =new File(path + "/" +name);
        FileInputStream in = new FileInputStream(image);
        byte[] ba = new byte[in.available()];
        Path path1 = Paths.get(path + "/" +name);
        in.read(ba);

        ImageItem it = new ImageItem(pic.getName(),ba,pic.getType());
//        it.setRealType(Files.probeContentType(path1));
        return  it ;
    }






    /**
     * 文件上
     * @param picture
     * @param request
     * @return
     */
    @RequestMapping("/upload")
    public Result upload(@RequestParam("picture") MultipartFile picture, HttpServletRequest request) {


        Log.logInfo("您已进入图片上传服务");
        //获取文件在服务器的储存位置

        File filePath = new File(path);
        Log.logInfo("文件的保存路径：" + path);
        if (!filePath.exists() && !filePath.isDirectory()) {
            Log.logInfo("目录不存在，创建目录:" + filePath);
            filePath.mkdir();
        }

        //获取原始文件名称(包含格式)
        String originalFileName = picture.getOriginalFilename();
        Log.logInfo("原始文件名称：" + originalFileName);

        //获取文件类型，以最后一个`.`为标识
        String type = originalFileName.substring(originalFileName.lastIndexOf(".") + 1);
        Log.logInfo("文件类型：" + type);
        //获取文件名称（不包含格式）
        String name = originalFileName.substring(0, originalFileName.lastIndexOf("."));

        // 获取时间字符串
        String dateTimeFormatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss").format(LocalDateTime.now());

        String fileName = dateTimeFormatter + UUID.randomUUID().toString().replaceAll("-","")  + "." + type;
        Log.logInfo("新文件名称：" + fileName);

        //在指定路径下创建一个文件
        File targetFile = new File(path, fileName);
        Log.logInfo("图片地址："+path+"/"+fileName);
        //将文件保存到服务器指定位置
        try {
            picture.transferTo(targetFile);
            Log.logInfo("上传成功");
            Pic pic =new Pic();
            pic.setName(fileName);
            pic.setPath(path.toString());
            pic.setType("image/"+ type);
            picService.saveOrUpdate(pic);
            Log.logInfo("插入图片数据" +pic.toString());
            //将文件在服务器的存储路径返回
            return Result.succ(208,fileName,fileName);
        }
        catch (IOException e) {
            Log.logInfo("上传失败");
            e.printStackTrace();
            return Result.fail(408, "上传失败",null);
        }
    }

    @PostMapping("/sendWeibo")
    public Result getJsonVal(@RequestBody Map<String,Object> content) {
        Log.logInfo("当前用户发送微博,新增用户信息到数据库");
        String ip= (String) content.get("ipAddr");
        String userid =  content.get("userid").toString();
        Log.logInfo("用户id是："+userid);


        String username = (String) content.get("username");
        Log.logInfo("用户名是："+username);
        String msg = (String) content.get("content");
        Log.logInfo("内容是:" + msg);
        String pic = (String) content.get("imageUrl");
        Log.logInfo("内容是:" + msg);
        Weibo temp =  weiboService.getOne(new QueryWrapper<Weibo>().eq("userid",userid).orderByDesc("date").last("limit 0,1"));




//        System.out.println(temp.getDate());
if (temp!=null)
{
    LocalDateTime tempDate = temp.getDate();

  if ( LocalDateTime.now().getDayOfYear()== tempDate.getDayOfYear())
  {
      int hour =LocalDateTime.now().getHour()- tempDate.getHour();
        if (hour==0)hour=24;
      return Result.fail(402,"发送失败,当前用户已经发过了，请你"+hour+"小时后再发",hour);
  }
}




    String ipName = (String) content.get("ipName");
    String ipId = (String) content.get("ipId");


        Weibo weibo =new Weibo();



        try {
            weibo.setUserid(userid);
            weibo.setUsername(username);
            weibo.setIpAddress(ip);
            msg+= "http://pzforest.com";
            weibo.setContent(msg);
            weibo.setDate(LocalDateTime.now());
            weibo.setIp_id(ipId);
            weibo.setIp_name(ipName);

//如果有图片,发图片和文字
           if (content.get("imageUrl")!=null)
           {
                ImageItem imgitem = getPicFile(pic);
                weibo.setPic(pic);
                weiboService.shareStatusWithPic(msg,imgitem);
                Log.logInfo("发送了文字和图片！" + msg +"图片是" + pic);
            }
//           如果没图片，只发文字
            if (content.get("imageUrl")==null)
            {
                weiboService.SendWeibo(msg);
                Log.logInfo("发送文字"+ msg);
            }

            weiboService.saveOrUpdate(weibo);
        }catch (Exception e)
        {
            Log.logDebug(e.toString());
            return  Result.fail(401,"发送失败",null);
        }
        finally {

        }



return  Result.succ(201,"发送成功",null);
    }

}
